<template>
    <div class="document-detail-container">
        <a-page-header :title="document?.file_name || '文档详情'" @back="goBack" style="padding: 16px 0; background: #fff;">
            <template #extra>
                <a-space>
                    <a-button @click="handleDownload">
                        <template #icon><download-outlined /></template>
                        下载文档
                    </a-button>
                    <a-button type="primary" @click="handleParse" v-if="canParse">
                        <template #icon><sync-outlined /></template>
                        解析文档
                    </a-button>
                </a-space>
            </template>
        </a-page-header>

        <a-row :gutter="16" class="content-wrapper">
            <!-- 左侧文档信息 -->
            <a-col :span="6">
                <a-card title="文档信息" :bordered="false">
                    <a-descriptions :column="1" bordered>
                        <a-descriptions-item label="文档名称">
                            {{ document?.file_name }}
                        </a-descriptions-item>
                        <a-descriptions-item label="知识库类型">
                            <a-tag :color="getCategoryColor(document?.knowledge_base_category)">
                                {{ getCategoryText(document?.knowledge_base_category) }}
                            </a-tag>
                        </a-descriptions-item>
                        <a-descriptions-item label="页数">
                            {{ document?.page_count || '未知' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="解析状态">
                            <a-tag :color="getParsingStatusColor(document?.parsing_status)">
                                {{ getParsingStatusText(document?.parsing_status) }}
                            </a-tag>
                        </a-descriptions-item>
                        <a-descriptions-item label="总结状态">
                            <a-tag :color="getSummaryStatusColor(document?.summary_status)">
                                {{ getSummaryStatusText(document?.summary_status) }}
                            </a-tag>
                        </a-descriptions-item>
                        <a-descriptions-item label="创建时间">
                            {{ formatDate(document?.created_at) }}
                        </a-descriptions-item>
                        <a-descriptions-item label="更新时间">
                            {{ formatDate(document?.updated_at) }}
                        </a-descriptions-item>
                    </a-descriptions>

                    <a-divider />

                    <div v-if="document?.parsing_error" class="error-section">
                        <a-alert type="error" :message="'解析错误'" :description="document.parsing_error" show-icon />
                    </div>
                </a-card>
            </a-col>

            <!-- 右侧PDF预览 -->
            <a-col :span="18">
                <a-card :bordered="false" class="pdf-preview-card">
                    <template #title>
                        <div class="pdf-controls">
                            <a-space>
                                <a-button-group>
                                    <a-button @click="zoomOut" :disabled="scale <= 0.5">
                                        <template #icon><zoom-out-outlined /></template>
                                    </a-button>
                                    <a-button @click="zoomIn" :disabled="scale >= 2">
                                        <template #icon><zoom-in-outlined /></template>
                                    </a-button>
                                </a-button-group>
                                <a-select v-model:value="currentPage" style="width: 100px">
                                    <a-select-option v-for="page in totalPages" :key="page" :value="page">
                                        第 {{ page }} 页
                                    </a-select-option>
                                </a-select>
                                <span class="page-info">/ {{ totalPages }} 页</span>
                            </a-space>
                        </div>
                    </template>
                    <div class="pdf-container" ref="pdfContainer">
                        <vue-pdf-embed v-if="document?.file_url" :source="document.file_url" :page="currentPage"
                            :scale="scale" @rendered="handlePageRendered" @loading="handleLoading" @error="handleError"
                            @num-pages="handleNumPages" />
                        <div v-else class="no-pdf">
                            <a-empty description="暂无PDF文件" />
                        </div>
                    </div>
                </a-card>
            </a-col>
        </a-row>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import VuePdfEmbed from 'vue-pdf-embed';
import {
    DownloadOutlined,
    SyncOutlined,
    ZoomInOutlined,
    ZoomOutOutlined,
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import {
    getKnowledgeBaseDocument,
    parseKnowledgeBaseDocument,
    OriginalDocument
} from '@/api/knowledge';

const route = useRoute();
const router = useRouter();
const document = ref<OriginalDocument | null>(null);
const loading = ref(false);
const currentPage = ref(1);
const totalPages = ref(1);
const scale = ref(1);
const pdfContainer = ref<HTMLElement | null>(null);

// 是否可以解析文档
const canParse = computed(() => {
    return document.value?.parsing_status !== 'completed' &&
        document.value?.parsing_status !== 'processing';
});

// 获取文档详情
const fetchDocument = async () => {
    const documentId = route.params.id;
    if (!documentId) {
        message.error('文档ID不存在');
        return;
    }

    loading.value = true;
    try {
        const data = await getKnowledgeBaseDocument(documentId as string);
        document.value = data;
    } catch (error) {
        message.error('获取文档详情失败');
    } finally {
        loading.value = false;
    }
};

// 返回上一页
const goBack = () => {
    router.back();
};

// 下载文档
const handleDownload = () => {
    if (document.value?.file_url) {
        window.open(document.value.file_url, '_blank');
    }
};

// 解析文档
const handleParse = async () => {
    if (!document.value) return;

    try {
        await parseKnowledgeBaseDocument(document.value.id);
        message.success('文档解析任务已提交');
        fetchDocument();
    } catch (error) {
        message.error('文档解析任务提交失败');
    }
};

// PDF预览相关方法
const handlePageRendered = () => {
    // 页面渲染完成
};

const handleLoading = (loading: boolean) => {
    // 处理加载状态
};

const handleError = (error: Error) => {
    message.error('PDF加载失败：' + error.message);
};

const handleNumPages = (numPages: number) => {
    totalPages.value = numPages;
};

// 缩放控制
const zoomIn = () => {
    if (scale.value < 2) {
        scale.value = Math.min(2, scale.value + 0.1);
    }
};

const zoomOut = () => {
    if (scale.value > 0.5) {
        scale.value = Math.max(0.5, scale.value - 0.1);
    }
};

// 工具方法
const getCategoryColor = (category?: string) => {
    switch (category) {
        case 'expert_consensus': return 'red';
        case 'detection_report': return 'green';
        case 'csco': return 'blue';
        case 'nccn': return 'purple';
        case 'other': return 'orange';
        default: return 'default';
    }
};

const getCategoryText = (category?: string) => {
    const categoryMap: Record<string, string> = {
        'expert_consensus': '专家共识',
        'detection_report': '检测报告',
        'csco': 'CSCO',
        'nccn': 'NCCN',
        'other': '其他'
    };
    return category ? categoryMap[category] || category : '';
};

const getParsingStatusColor = (status?: string) => {
    switch (status) {
        case 'pending': return 'default';
        case 'processing': return 'processing';
        case 'completed': return 'success';
        case 'failed': return 'error';
        default: return 'default';
    }
};

const getParsingStatusText = (status?: string) => {
    switch (status) {
        case 'pending': return '待解析';
        case 'processing': return '解析中';
        case 'completed': return '已完成';
        case 'failed': return '解析失败';
        default: return status || '';
    }
};

const getSummaryStatusColor = (status?: string) => {
    switch (status) {
        case 'pending': return 'default';
        case 'processing': return 'processing';
        case 'completed': return 'success';
        case 'failed': return 'error';
        default: return 'default';
    }
};

const getSummaryStatusText = (status?: string) => {
    switch (status) {
        case 'pending': return '待总结';
        case 'processing': return '总结中';
        case 'completed': return '已完成';
        case 'failed': return '总结失败';
        default: return status || '';
    }
};

const formatDate = (date?: string) => {
    if (!date) return '';
    return dayjs(date).format('YYYY-MM-DD HH:mm');
};

onMounted(() => {
    fetchDocument();
});
</script>

<style scoped>
.document-detail-container {
    padding: 0;
    background: #f0f2f5;
    min-height: 100vh;
}

.content-wrapper {
    padding: 16px;
}

.pdf-preview-card {
    height: calc(100vh - 180px);
    display: flex;
    flex-direction: column;
}

.pdf-controls {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
}

.page-info {
    color: rgba(0, 0, 0, 0.45);
}

.pdf-container {
    flex: 1;
    overflow: auto;
    padding: 16px;
    display: flex;
    justify-content: center;
    background: #f5f5f5;
}

.no-pdf {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.error-section {
    margin-top: 16px;
}

:deep(.ant-card-head) {
    border-bottom: none;
}

:deep(.ant-descriptions-item-label) {
    width: 120px;
    background-color: #fafafa;
}
</style>